$(function () {
    $("#jqGrid").Grid({
        url: '../stock/route/list',
        colModel: [
			{label: 'id', name: 'id', index: 'id', key: true, hidden: true},
			{label: '车型', name: 'productId', index: 'product_id', hidden: true},
			{label: '门店', name: 'branchName', index: 'branch_id', width: 80},
			{label: '操作员', name: 'personName', index: 'personName', width: 80},
			{label: '导入日期', name: 'routeDate', index: 'route_date', width: 80},
			{label: '车辆类型', name: 'productVo.carType', index: 'code', width: 80},
			{label: '品牌', name: 'productVo.carSerie', index: 'car_serie', width: 80},
			{label: '代码', name: 'productVo.code', index: 'code', width: 80},
			{label: '车型', name: 'productVo.carModel', index: 'car_model', width: 80},
			{label: '款式', name: 'productVo.design', index: 'design', width: 80},
			{label: 'VIN码', name: 'vin', index: 'vin', width: 80},
			{label: '发动机号', name: 'engine', index: 'engine', width: 80},
			{label: '厂家指导价格', name: 'guidePrice', index: 'guidePrice', width: 80},
			{label: '配置', name: 'productVo.config', index: 'config', width: 80},
			{label: '外观', name: 'productVo.colour', index: 'colour', width: 80},
			{label: '排量', name: 'productVo.displacement', index: 'displacement', width: 80},
			{label: '变速箱', name: 'productVo.speedBox', index: 'speedBox', width: 80},
			{label: '动力', name: 'productVo.power', index: 'power', width: 80},
			{label: '选装', name: 'optional', index: 'optional', width: 80},
			{label: '备注', name: 'content', index: 'content', width: 80}]
    });

    $(window).resize(function () {
        $("#detailInnerTable").setGridWidth($(window).width() - 450);
    });
    var autoWidth = ($(window).width() - 450) / 13;
    
    Ajax.request({
        url: "../product/qualifier/queryAll",
        contentType: "application/json",
        successCallback: function (r) {
        	$("#detailInnerTable").Grid({
                datatype: "local",
                data:vm.stockReal.productList,
                cellEdit: true,  //开启表格编辑
                cellsubmit: 'clientArray',//remote代表每次编辑提交后进行服务器保存，clientArray只保存到数据表格不保存到服务器
                height: 250,
                shrinkToFit: false,
                autoScroll:true,//设置水平滚动条
                left:90,
                rowNum:99999,
                page: false,
                rowList: false,
                colModel: [
                    {label: 'id', name: 'id', index: 'id', hidden: true},
                    {label: '车型名称', name: 'productName',editable: false},
                    {label: 'VIN码', name: 'vin', align: 'center', valign: 'middle'},
                    {label: '发动机号', name: 'engine', align: 'center', valign: 'middle'},
                    {label: '厂家指导价格(元)', name: 'guidePrice', align: 'center', valign: 'middle'},
                    {label: '合格证', name: 'qualifierId', editable: true,align: 'center',valign: 'middle',edittype: 'select',
                    	editoptions:{value:r.dict}
                    }
                ],
                beforeEditCell: function (rowid, cellname, v, iRow, iCol) {
                    vm.lastEditRow = iRow;
                    vm.lastEditCell = iCol;
                },
                beforeSubmitCell:function(rowid, cellname, value, iRow, iCol){
                    for (var i = 0; i < vm.stockReal.productList.length; i++) {
                        if(vm.stockReal.productList[i].id==rowid){
                            vm.stockReal.productList[i][cellname]=value;
                            break;
                        }
                    }
                }
            });
        }
    });
});

var vm = new Vue({
	el: '#rrapp',
	data: {
        showList: true,
        showAdd:false,
        routeShow:false,
        modalImport:false,
        title: null,
		stockRoute: {},
        stockReal:{},
        ruleStorageValidate: {
			storageName: [
				{required: true, message: '仓库不能为空', trigger: 'blur'}
			]
		},
		ruleValidate : {
//			storageName: [
//			              {required: true, message: '仓库不能为空', trigger: 'blur'}
//			              ]
		},
		q: {
            name:"",
            productName:"",
            personName:"",
            carVin:"",
            engine:"",
            startDate:"",
            endDate:""
        }
	},
	methods: {
		showImport:function(){
			vm.modalImport=true;
			$('.ivu-upload-list li').remove();
		},
		reloadImport:function(){
			vm.modalImport=false;
		},
		downFile: function () {
            //下载模板
            window.location.href = "../statics/model/carRoute.xlsx";
        },
        impsuccess: function (res, file) {
            alert('导入成功', function (index) {
                vm.reload();
                vm.modal = false;
            });
        },
        imperror: function () {
            alert('导入失败，请下载模板并根据模板数据进行导入', function (index) {
                vm.reload();
            });
        },
        dateChange:function(val){
            console.log(val)
            vm.q.startDate=val[0];
            vm.q.endDate=val[1];
        },
		selectProductCar:function(){
			openWindow({
            	type: 2,
                title: "选择车型",
                area: ['80%', '60%'],
                content: ['../product/productcar.html'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#jqGrid');
                	vm.stockRoute.productId=selectRowData.id;
                	vm.stockRoute.productName=selectRowData.carSerie+" "+selectRowData.carModel+" "+selectRowData.design+" "+selectRowData.config+" "+selectRowData.colour;
                    layer.close(index);
                }
            });
    	},
        selectStorage:function(){
            openWindow({
                type: 2,
                title: "选择仓库",
                area: ['80%', '60%'],
                content: ['../product/storageinfo.html'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                    var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#jqGrid');
                    vm.stockReal.storageId=selectRowData.id;
                    vm.stockReal.storageName=selectRowData.name;
                    layer.close(index);
                }
            });
        },
        delRow:function(){
            var id = getSelectedRow("#detailInnerTable");
            if (id == null) {
                return;
            }
            var otherDataList=[];
            for (var i = 0; i < vm.stockReal.productList.length; i++) {
                if(vm.stockReal.productList[i].id==id){
                    continue;
                }
                otherDataList.push(vm.stockReal.productList[i]);
            }
            vm.stockReal.productList=otherDataList;
            vm.reloadDetail();
        },
		query: function () {
			vm.reload();
		},
		add: function () {
			vm.showList = false;
            vm.routeShow=false;
            vm.showAdd = true;
			vm.title = "新增";
			vm.stockRoute = {productId:null,productName:""};
		},
		update: function (event) {
            var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
            vm.routeShow=false;
			vm.showList = false;
            vm.showAdd = true;
            vm.title = "修改";
            vm.getInfo(id);
		},
        addLibrary:function(){
            vm.title = "入库";
            vm.showList = false;
            vm.showAdd = false;
            vm.routeShow=true;
            vm.stockReal={storageName:""};
            var ids = getSelectedRows("#jqGrid");
            if (ids == null){
                return;
            }
            Ajax.request({
                url: "../stock/route/selectStockRouteList",
                params: JSON.stringify(ids),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    vm.stockReal.productList = r.data;
                }
            });
            vm.reloadDetail();
		},
		saveOrUpdate: function (event) {
            var url = vm.stockRoute.id == null ? "../stock/route/save" : "../stock/route/update";
            var productionDate=vm.stockRoute.productionDate;
            vm.stockRoute.productionDate=formatDateToDate(productionDate);
            Ajax.request({
			    url: url,
                params: JSON.stringify(vm.stockRoute),
                type: "POST",
			    contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
			});
		},
		del: function (event) {
            var ids = getSelectedRows("#jqGrid");
			if (ids == null){
				return;
			}

			confirm('确定要删除选中的记录？', function () {
                Ajax.request({
				    url: "../stock/route/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
				    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
					}
				});
			});
		},
		getInfo: function(id){
            Ajax.request({
                url: "../stock/route/info/"+id,
                async: true,
                successCallback: function (r) {
                    vm.stockRoute = r.stockRoute;
                }
            });
		},
		reload: function (event) {
			vm.showList = true;
            vm.showAdd = false;
            vm.routeShow=false;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
			$("#jqGrid").jqGrid('setGridParam', {
                postData: vm.q,
                page: 1
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
		},
        reloadDetail:function(){
            $("#detailInnerTable").jqGrid('clearGridData');  //清空表格
            $("#detailInnerTable").jqGrid('setGridParam', {  // 重新加载数据
                datatype: 'local',
                data: vm.stockReal.productList,   //  data 是符合格式要求的需要重新加载的数据
                page: 1
            }).trigger("reloadGrid");
        },
        reloadSearch: function() {
            vm.q = {
                name:"",
                productName:"",
                personName:"",
                carVin:"",
                engine:"",
                startDate:"",
                endDate:""
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
		submitStockReal:function (name) {
            handleSubmitValidate(this, name, function () {
                $('#detailInnerTable').jqGrid("saveCell", vm.lastEditRow, vm.lastEditCell);
                if(!vm.stockReal.storageName||!vm.stockReal.storageId){
                	alert("仓库不能为空");
                	return;
                }
                var url = "../stock/real/saveBatch";
                Ajax.request({
                    url: url,
                    params: JSON.stringify(vm.stockReal),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        }
	}
});